
package models.spider.index;

import static models.Store.delete;
import static models.Store.save;

import java.util.Date;
import java.util.List;

import javax.persistence.TypedQuery;

import org.apache.commons.lang3.StringUtils;

/**
 * 
 * @author laurent@opprecht.info
 */
public class Index {

    protected int errorThreshold = 5;

    public Index(final int errorThreshold) {
        this.errorThreshold = errorThreshold;
    }

    public Index() {
        this(5);
    }

    public int getErrorThreshold() {
        return errorThreshold;
    }

    public boolean has(final String url) {
        boolean missing = (Entry.find.byUrl(url) == null);
        return !missing;
    }

    public Entry get(final String url) {
        return Entry.find.byUrl(url);
    }

    public List<Entry> before(final Date date) {
        TypedQuery<Entry> query = Entry.find.before(date);
        List<Entry> result = query.getResultList();
        return result;
    }

    public Entry bottom(final Date date) {
        TypedQuery<Entry> query = Entry.find.before(date).setMaxResults(1);
        List<Entry> items = query.getResultList();
        for (Entry item : items) {
            return item;
        }
        return null;
    }

    public void success(final Entry entry) {
        entry.setErrors(0);
        entry.setModified(new Date());
        save(entry);
    }

    public void success(final String url) {
        if (StringUtils.isEmpty(url)) {
            return;
        }
        success(get(url));
    }

    public void failure(final String url) {
        if (StringUtils.isEmpty(url)) {
            return;
        }
        failure(get(url));
    }

    public void failure(final Entry entry) {
        entry.setErrors(entry.getErrors() + 1);
        entry.setModified(new Date());
        if (entry.getErrors() > errorThreshold) {
            remove(entry);
        } else {
            save(entry);
        }
    }

    public void add(final String url) {
        if (has(url)) {
            return;
        }
        Entry entry = Entry.get(url);
        save(entry);
    }

    public void remove(final String url) {
        remove(get(url));
    }

    public void remove(final Entry entry) {
        delete(entry);
    }
}
